package com.cdtye.itps.cms.controller.algorithm;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdtye.common.authcore.model.UserSso;
import com.cdtye.common.authcore.util.AuthHelper;
import com.cdtye.common.webcore.base.BaseController;
import com.cdtye.common.webcore.constants.WebConstants;
import com.cdtye.common.webcore.util.DateUtil;
import com.cdtye.common.webcore.web.AjaxJson;
import com.cdtye.common.webcore.web.BizException;
import com.cdtye.itps.cms.config.CmsConfig;
import com.cdtye.itps.cms.dao.algorithm.entity.JcjcAlgorithmOperateLog;
import com.cdtye.itps.cms.dao.algorithm.vo.JcjcAlgorithmOperateLogVo;
import com.cdtye.itps.cms.service.algorithm.JcjcAlgorithmOperateLogService;
import com.cdtye.itps.cms.util.DateUtils;
import com.cdtye.itps.cms.util.PythonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: wangzhong
 * @Date: 2023/9/12 14:29
 * @Description:
 **/

@Api(tags="算法操作日志表接口")
@RestController
@RequestMapping("/JcjcAlgorithmOperateLog")
public class JcjcAlgorithmOperateLogController extends BaseController {

    @Autowired
    private JcjcAlgorithmOperateLogService modelService;

    @Autowired
    private CmsConfig cmsConfig;

    @ApiOperation(value = "保存或更新", notes = "返回对象最新数据")
    @PostMapping(value = "/saveOrUpdate")
    public AjaxJson<JcjcAlgorithmOperateLog> saveOrUpdate(@Valid JcjcAlgorithmOperateLog model){
        UserSso loginUser = AuthHelper.loginUser();
        Date nowDate = DateUtil.getDateTime();

        if(StringUtils.isBlank(model.getId())){
            model.setCreateBy(loginUser.getId());
            model.setCreateDatetime(nowDate);
            model.setUpdateDatetime(nowDate);
            //初始化删除状态
            model.setDelFlag(WebConstants.NO);
        }else{
            JcjcAlgorithmOperateLog oldModel = modelService.getById(model.getId());
            if(oldModel==null){
                return error("未查询到修改对象");
            }
            bindRequestToModel(oldModel);
            model = oldModel;
        }
        model.setUpdateBy(loginUser.getId());
        model.setUpdateDatetime(nowDate);
        modelService.saveOrUpdate(model);
        return success(model);
    }

    @ApiOperation(value = "按ID删除")
    @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "String")
    @PostMapping(value = "/{id}")
    public AjaxJson deleteById(@PathVariable("id") String id) {
        if(StringUtils.isBlank(id)){
            return error("未获取到参数");
        }
        modelService.removeById(id);
        return success();
    }

    @ApiOperation(value = "按ID状态删除")
    @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "String")
    @PostMapping(value = "/deleteFlagById")
    public AjaxJson deleteFlagById(String id) throws Exception{
        if(StringUtils.isBlank(id)){
            return error("未获取到参数");
        }
        modelService.deleteFlagById(id);
        return success();
    }

    @ApiOperation(value = "按ID查询")
    @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "String")
    @GetMapping(value = "/{id}")
    public AjaxJson getById(@PathVariable("id") String id) {
        if(StringUtils.isBlank(id)){
            return error("未获取到参数");
        }
        return success(modelService.getById(id));
    }

    @ApiOperation(value = "列表查询")
    @GetMapping(value = "/list")
    public AjaxJson<List<JcjcAlgorithmOperateLog>> list(JcjcAlgorithmOperateLogVo vo){
        List<JcjcAlgorithmOperateLog> result = modelService.list(vo);
        return success(result);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/listPage")
    public AjaxJson<IPage<Map<String,Object>>> listPage(JcjcAlgorithmOperateLogVo vo){
        IPage<Map<String,Object>> result = modelService.listPage(vo);
        return success(result);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public AjaxJson handleFileUpload(@RequestParam("file") MultipartFile file, String type) {
        if (file.isEmpty()) {
            // 如果文件为空，返回错误信息
            return AjaxJson.error();
        }

        try {
            // 创建一个File对象，表示要上传的目标位置
            String fileName = DateUtils.DateToString(new Date(),"yyyyMMddHHmmss")+"_"+file.getOriginalFilename();
            File destFile = new File(cmsConfig.getAlgorithmDirectory(), fileName);
            int dotIndex = fileName.lastIndexOf('.');
            String dot = fileName.substring(dotIndex);
            String filePath = cmsConfig.getAlgorithmDirectory()+fileName.replace(dot,"")+"_revised.xlsx";
            if (type.equals("2")) {
                filePath = cmsConfig.getAlgorithmDirectory()+fileName.replace(dot,"")+"_filtered.xlsx";
            }
            // 将上传的文件复制到目标位置
            file.transferTo(destFile);
            UserSso loginUser = AuthHelper.loginUser();
            Date nowDate = DateUtil.getDateTime();
            JcjcAlgorithmOperateLog log = new JcjcAlgorithmOperateLog();
            log.setCreateBy(loginUser.getId());
            log.setCreateDatetime(nowDate);
            log.setUpdateDatetime(nowDate);
            //初始化删除状态
            log.setDelFlag(WebConstants.NO);
            log.setSourceUrl(cmsConfig.getAlgorithmDirectory()+fileName);
            log.setResultUrl(filePath);
//            log.setSourceUrl("D:\\"+fileName);
            log.setStatus("0");
            log.setFileName(file.getOriginalFilename());
            log.setType(type);
            modelService.save(log);
            // 文件上传成功
            return AjaxJson.success();
        } catch (IOException e) {
            // 文件上传失败，返回错误信息
            return AjaxJson.error(e.getMessage());
        }
    }

    @ApiOperation(value = "计算")
    @GetMapping(value = "/")
    public AjaxJson<String> algorithm(String id){
        JcjcAlgorithmOperateLog log = modelService.getById(id);
        if (log==null) {
            return error("数据不存在");
        }
        String py = "/usr/bin/python";
        String pyName = null;
        if (StringUtils.equals("1",log.getType())) {
            pyName = cmsConfig.getAlgorithmDirectory()+"mileage_correction.py";
        }else {
            pyName = cmsConfig.getAlgorithmDirectory()+"validation_mileage.py";
        }
        String result = PythonUtil.transfer(py, pyName, log.getSourceUrl());
        log.setStatus("1");
        log.setUpdateDatetime(new Date());
        modelService.updateById(log);
        return success(result);
    }

    @ApiOperation(value = "下载结果文件")
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, String id) {
        ServletOutputStream out = null;
        try {
            JcjcAlgorithmOperateLog log = modelService.getById(id);
            String filePath = log.getResultUrl();
            String name = new File(filePath).getName();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            FileInputStream in = new FileInputStream(filePath);
            out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            throw new BizException("下载文件出错");
        }finally {
            try {
                if (out != null){
                    out.close();
                }
            }catch (Exception e){
                throw new BizException("导出 : 关闭输出流失败");
            }
        }
    }
}

